'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'

export default function DebugAuthPage() {
  const [authStatus, setAuthStatus] = useState<any>(null)
  const [permissionsStatus, setPermissionsStatus] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [cookies, setCookies] = useState<string>('')

  const checkAuthStatus = async () => {
    setLoading(true)
    try {
      // 检查认证状态
      const authResponse = await fetch('/api/auth/me')
      const authData = await authResponse.json()
      setAuthStatus(authData)

      // 检查权限状态
      const permResponse = await fetch('/api/auth/permissions?tableName=table_c2')
      const permData = await permResponse.json()
      setPermissionsStatus(permData)

    } catch (error) {
      console.error('检查状态失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const testLogin = async () => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          username: 'design', 
          password: 'design123' 
        }),
      })

      const data = await response.json()
      console.log('登录结果:', data)
      
      // 登录后重新检查状态
      setTimeout(checkAuthStatus, 1000)
    } catch (error) {
      console.error('登录失败:', error)
    }
  }

  useEffect(() => {
    checkAuthStatus()
    // 只在客户端获取cookie信息
    if (typeof window !== 'undefined') {
      setCookies(document.cookie)
    }
  }, [])

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">认证状态调试</h1>
      
      <div className="flex space-x-4">
        <Button onClick={checkAuthStatus} disabled={loading}>
          {loading ? '检查中...' : '刷新状态'}
        </Button>
        <Button onClick={testLogin} variant="outline">
          测试登录 (design)
        </Button>
      </div>

      {/* 认证状态 */}
      <Card>
        <CardHeader>
          <CardTitle>认证状态 (/api/auth/me)</CardTitle>
        </CardHeader>
        <CardContent>
          {authStatus ? (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Badge variant={authStatus.success ? 'default' : 'destructive'}>
                  {authStatus.success ? '已登录' : '未登录'}
                </Badge>
              </div>
              
              {authStatus.success && authStatus.data ? (
                <div className="space-y-1 text-sm">
                  <div><strong>用户名:</strong> {authStatus.data.user.username}</div>
                  <div><strong>姓名:</strong> {authStatus.data.user.full_name}</div>
                  <div><strong>角色:</strong> {authStatus.data.user.role_name} ({authStatus.data.user.role_code})</div>
                </div>
              ) : (
                <div className="text-red-600">{authStatus.error}</div>
              )}
            </div>
          ) : (
            <div>加载中...</div>
          )}
        </CardContent>
      </Card>

      {/* 权限状态 */}
      <Card>
        <CardHeader>
          <CardTitle>权限状态 (/api/auth/permissions)</CardTitle>
        </CardHeader>
        <CardContent>
          {permissionsStatus ? (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Badge variant={permissionsStatus.success ? 'default' : 'destructive'}>
                  {permissionsStatus.success ? '权限正常' : '权限错误'}
                </Badge>
              </div>
              
              {permissionsStatus.success && permissionsStatus.data ? (
                <div className="space-y-1 text-sm">
                  <div><strong>管理员权限:</strong> {permissionsStatus.data.permissions.canEditAll ? '是' : '否'}</div>
                  <div><strong>数据来源权限:</strong> {permissionsStatus.data.permissions.dataSourceAccess.join(', ')}</div>
                  <div><strong>可编辑字段数:</strong> {permissionsStatus.data.permissions.editableFields?.length || 0}</div>
                </div>
              ) : (
                <div className="text-red-600">{permissionsStatus.error}</div>
              )}
            </div>
          ) : (
            <div>加载中...</div>
          )}
        </CardContent>
      </Card>

      {/* Cookie 信息 */}
      <Card>
        <CardHeader>
          <CardTitle>Cookie 信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <div><strong>所有 Cookies:</strong></div>
            <pre className="bg-gray-100 p-2 rounded text-xs overflow-auto">
              {cookies || '无 Cookie'}
            </pre>
          </div>
        </CardContent>
      </Card>

      {/* 原始数据 */}
      <Card>
        <CardHeader>
          <CardTitle>原始响应数据</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div>
              <h4 className="font-medium mb-2">认证响应:</h4>
              <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto max-h-48">
                {JSON.stringify(authStatus, null, 2)}
              </pre>
            </div>
            
            <div>
              <h4 className="font-medium mb-2">权限响应:</h4>
              <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto max-h-48">
                {JSON.stringify(permissionsStatus, null, 2)}
              </pre>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
